import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  SafeAreaView,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import { useTranslation } from 'react-i18next';
import Toast from 'react-native-simple-toast';
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome';
import { faEye, faEyeSlash } from '@fortawesome/free-solid-svg-icons';
import CryptoJS from 'crypto-js';
import { faSquare, faSquareCheck } from '@fortawesome/free-regular-svg-icons';
import theme from '../../utils/theme';
import { registApi, sendVerificationCodeApi } from '../../http/api.js';
import StorageUtil from '../../utils/StorageUtil';
import { useDispatch } from 'redux-react-hook';
import NavigationBar from '../../components/NavigationBar';

const RegisterView = ({ navigation }) => {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const [formData, setFormData] = useState({
    email: '',
    verificationCode: '',
    password: '',
    confirmPassword: '',
  });
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [isSendingCode, setIsSendingCode] = useState(false);
  const [agreedToTerms, setAgreedToTerms] = useState(false); // 新增：是否同意协议状态
  const [errors, setErrors] = useState({});

  // 倒计时效果
  useEffect(() => {
    let timer;
    if (countdown > 0) {
      timer = setTimeout(() => setCountdown(countdown - 1), 1000);
    }
    return () => clearTimeout(timer);
  }, [countdown]);

  // 更新表单数据
  const updateFormData = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // 清除对应字段的错误
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  // 邮箱验证
  const validateEmail = (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  // 密码强度验证
  const validatePassword = (password) => {
    // 至少6位
    return password.length >= 6;
  };

  // 发送验证码
  const handleSendVerificationCode = async () => {
    // 验证邮箱
    if (!formData.email.trim()) {
      setErrors(prev => ({ ...prev, email: t('register.emailRequired') }));
      return;
    }
    if (!validateEmail(formData.email)) {
      setErrors(prev => ({ ...prev, email: t('register.emailInvalid') }));
      return;
    }

    setIsSendingCode(true);
    try {
      const result = await sendVerificationCodeApi({
        email: formData.email.trim(),
        type: 'register' // 注册类型的验证码
      });
      
      if (result.code === 200) {
        Toast.show(t('register.codeSent'), Toast.SHORT);
        setCountdown(60); // 60秒倒计时
        // 清除邮箱错误
        setErrors(prev => ({ ...prev, email: '' }));
      } else {
        Toast.show(result.message || '发送失败', Toast.SHORT);
      }
    } catch (error) {
      console.error('Send verification code error:', error);
      if (error.message.includes('邮箱已存在')) {
        setErrors(prev => ({ ...prev, email: t('register.emailExists') }));
      } else {
        Toast.show(error.message || '发送失败', Toast.SHORT);
      }
    } finally {
      setIsSendingCode(false);
    }
  };

  // 表单验证
  const validateForm = () => {
    const newErrors = {};

    // 邮箱验证
    if (!formData.email.trim()) {
      newErrors.email = t('register.emailRequired');
    } else if (!validateEmail(formData.email)) {
      newErrors.email = t('register.emailInvalid');
    }

    // 验证码验证 - 仅验证是否为6位数字
    if (!formData.verificationCode.trim()) {
      newErrors.verificationCode = t('register.codeRequired');
    } else if (!/^\d{6}$/.test(formData.verificationCode)) {
      newErrors.verificationCode = t('register.codeInvalid');
    }

    // 密码验证 - 至少6位
    if (!formData.password.trim()) {
      newErrors.password = t('register.passwordRequired');
    } else if (!validatePassword(formData.password)) {
      newErrors.password = t('register.passwordTooShort');
    }

    // 确认密码验证
    if (!formData.confirmPassword.trim()) {
      newErrors.confirmPassword = t('register.confirmPasswordRequired');
    } else if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = t('register.passwordMismatch');
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 注册处理
  const handleRegister = async () => {
    if (!validateForm()) {
      return;
    }

    setIsLoading(true);
    try {
      // 加密密码
      const encryptedPassword = CryptoJS.SHA256(formData.password).toString();
      const param = {
        email: formData.email.trim(),
        verificationCode: formData.verificationCode.trim(),
        password: encryptedPassword,
        nickname: formData.email.trim(), // 使用邮箱作为默认昵称
        avatar: '', // 默认头像
        latitude: 0.0,
        longitude: 0.0
      }
      // 调用注册API - 包含验证码
      const result = await registApi(param);
      
      if (result.code === 200) {
        // 注册成功
        const { token, user } = result.data;
        
        // 保存token到本地存储
        await StorageUtil.setItem('user_token', token);
        
        // 更新Redux状态
        dispatch({
          type: 'SET_LOGIN',
          isLogin: true
        });
        
        Toast.show(t('register.success'), Toast.SHORT);
      } else {
        // 处理特定错误
        if (result.message.includes('验证码')) {
          setErrors({ verificationCode: t('register.codeInvalid') });
        } else {
          Toast.show(result.message || t('register.failed'), Toast.SHORT);
        }
      }
      
    } catch (error) {
      console.error('Register error:', error);
      
      // 处理特定错误
      if (error.message.includes('邮箱已存在')) {
        setErrors({ email: t('register.emailExists') });
      } else if (error.message.includes('验证码')) {
        setErrors({ verificationCode: t('register.codeInvalid') });
      } else {
        Toast.show(error.message || t('register.failed'), Toast.SHORT);
      }
    } finally {
      setIsLoading(false);
    }
  };

  // 返回登录页面
  const handleBackToLogin = () => {
    if (navigation.goBack) {
      navigation.goBack();
    } else if (navigation.navigate) {
      navigation.navigate('LoginView');
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <NavigationBar 
        title={t('register.title')}
        goBack={handleBackToLogin}
      />
      <KeyboardAvoidingView 
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardAvoid}
      >
        <View style={styles.content}>
          {/* 注册表单 */}
          <View style={styles.formContainer}>
            {/* 邮箱输入 */}
            <View style={styles.inputContainer}>
              <TextInput
                style={[styles.textInput, errors.email && styles.textInputError]}
                placeholder={t('register.emailPlaceholder')}
                placeholderTextColor={theme.colors.text.hint}
                value={formData.email}
                onChangeText={(value) => updateFormData('email', value)}
                keyboardType="email-address"
                autoCapitalize="none"
                autoCorrect={false}
                editable={!isLoading}
              />
              {errors.email && (
                <Text style={styles.errorText}>{errors.email}</Text>
              )}
            </View>

            {/* 验证码输入 */}
            <View style={styles.inputContainer}>
              <View style={styles.verificationContainer}>
                <TextInput
                  style={[styles.textInput, styles.verificationInput, errors.verificationCode && styles.textInputError]}
                  placeholder={t('register.verificationCodePlaceholder')}
                  placeholderTextColor={theme.colors.text.hint}
                  value={formData.verificationCode}
                  onChangeText={(value) => updateFormData('verificationCode', value)}
                  keyboardType="numeric"
                  maxLength={6}
                  editable={!isLoading}
                />
                <TouchableOpacity 
                  style={[
                    styles.sendCodeButton, 
                    countdown > 0 ? styles.sendCodeButtonCountdown : null,
                    isSendingCode && styles.sendCodeButtonSending
                  ]}
                  onPress={handleSendVerificationCode}
                  disabled={countdown > 0 || isSendingCode || isLoading}
                >
                  <Text style={[
                    styles.sendCodeText,
                    countdown > 0 ? styles.sendCodeTextCountdown : null,
                    isSendingCode && styles.sendCodeTextSending
                  ]}>
                    {isSendingCode ? t('register.sendingCode') : countdown > 0 ? `${countdown}s` : t('register.sendCode')}
                  </Text>
                </TouchableOpacity>
              </View>
              {errors.verificationCode && (
                <Text style={styles.errorText}>{errors.verificationCode}</Text>
              )}
            </View>

            {/* 密码输入 */}
            <View style={styles.inputContainer}>
              <View style={styles.passwordContainer}>
                <TextInput
                  style={[styles.textInput, styles.passwordInput, errors.password && styles.textInputError]}
                  placeholder={t('register.passwordPlaceholder')}
                  placeholderTextColor={theme.colors.text.hint}
                  value={formData.password}
                  onChangeText={(value) => updateFormData('password', value)}
                  secureTextEntry={!showPassword}
                  autoCapitalize="none"
                  autoCorrect={false}
                  editable={!isLoading}
                />
                <TouchableOpacity 
                  style={styles.eyeButton}
                  onPress={() => setShowPassword(!showPassword)}
                  disabled={isLoading}
                >
                  <FontAwesomeIcon 
                    icon={showPassword ? faEye : faEyeSlash} 
                    size={18} 
                    color={theme.colors.text.secondary}
                  />
                </TouchableOpacity>
              </View>
              {errors.password && (
                <Text style={styles.errorText}>{errors.password}</Text>
              )}
              <Text style={styles.passwordHint}>{t('register.passwordHint')}</Text>
            </View>

            {/* 确认密码输入 */}
            <View style={styles.inputContainer}>
              <View style={styles.passwordContainer}>
                <TextInput
                  style={[styles.textInput, styles.passwordInput, errors.confirmPassword && styles.textInputError]}
                  placeholder={t('register.confirmPasswordPlaceholder')}
                  placeholderTextColor={theme.colors.text.hint}
                  value={formData.confirmPassword}
                  onChangeText={(value) => updateFormData('confirmPassword', value)}
                  secureTextEntry={!showConfirmPassword}
                  autoCapitalize="none"
                  autoCorrect={false}
                  editable={!isLoading}
                />
                <TouchableOpacity 
                  style={styles.eyeButton}
                  onPress={() => setShowConfirmPassword(!showConfirmPassword)}
                  disabled={isLoading}
                >
                  <FontAwesomeIcon 
                    icon={showConfirmPassword ? faEye : faEyeSlash} 
                    size={18} 
                    color={theme.colors.text.secondary}
                  />
                </TouchableOpacity>
              </View>
              {errors.confirmPassword && (
                <Text style={styles.errorText}>{errors.confirmPassword}</Text>
              )}
            </View>

            {/* 注册按钮 */}
            <TouchableOpacity 
              style={[
                styles.registerButton, 
                (isLoading || !agreedToTerms) && styles.registerButtonDisabled
              ]}
              onPress={handleRegister}
              disabled={isLoading || !agreedToTerms}
            >
              <Text style={styles.registerButtonText}>
                {isLoading ? t('register.registering') : t('register.register')}
              </Text>
            </TouchableOpacity>

          </View>
          
                      {/* 协议同意复选框 */}
            <View style={styles.agreementCheckContainer}>
              <TouchableOpacity activeOpacity={1} onPress={() => setAgreedToTerms(!agreedToTerms)} disabled={isLoading} style={styles.checkboxContainer}>
                <FontAwesomeIcon size={20} icon={agreedToTerms ? faSquareCheck : faSquare} color={theme.colors.primary.main}/>
                <Text style={[styles.agreementText,{marginLeft: 4}]}>
                    {t('register.agreementPrefix')}
                </Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => {
                    navigation.navigate('UserAgreement');
                  }}>
                    <Text style={styles.agreementLink}>
                      {t('register.userAgreement')}
                    </Text>
                  </TouchableOpacity>
                  <Text style={styles.agreementText}> {t('register.and')} </Text>
                  <TouchableOpacity onPress={() => {
                    navigation.navigate('PrivacyPolicy');
                  }}>
                    <Text style={styles.agreementLink}>
                      {t('register.privacyPolicy')}
                    </Text>
              </TouchableOpacity>
            </View>
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme.colors.background.primary,
  },
  keyboardAvoid: {
    flex: 1,
  },
  content: {
    flex: 1,
    paddingHorizontal: theme.spacing.lg,
    paddingTop: theme.spacing.lg,
  },
  
  // 表单样式
  formContainer: {
    flex: 1,
    paddingBottom: theme.spacing.xl,
  },
  
  // 输入框样式
  inputContainer: {
    marginBottom: theme.spacing.lg,
  },
  textInput: {
    ...theme.typography.body.large,
    backgroundColor: theme.colors.background.secondary,
    borderWidth: 1,
    borderColor: theme.colors.border.light,
    borderRadius: theme.borderRadius.md,
    paddingHorizontal: theme.spacing.md,
    paddingVertical: theme.spacing.sm,
    color: theme.colors.text.primary,
    minHeight: 48,
    textAlignVertical: 'center',
  },
  textInputError: {
    borderColor: theme.colors.error,
  },
  passwordContainer: {
    position: 'relative',
  },
  passwordInput: {
    paddingRight: 50,
  },
  eyeButton: {
    position: 'absolute',
    right: theme.spacing.md,
    top: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    width: 30,
  },
  errorText: {
    ...theme.typography.body.small,
    color: theme.colors.error,
    marginTop: theme.spacing.xs,
    marginLeft: theme.spacing.sm,
  },
  passwordHint: {
    ...theme.typography.body.small,
    color: theme.colors.text.hint,
    marginTop: theme.spacing.xs,
    marginLeft: theme.spacing.sm,
  },
  
  // 协议同意复选框样式
  agreementCheckContainer: {
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'center',
    // backgroundColor: 'red'
  },
  checkboxContainer: {
    // flexDirection: 'row',
    // alignItems: 'center',
    // justifyContent: 'center',
    // backgroundColor: 'red'
  },
  checkbox: {
    width: 20,
    height: 20,
    borderWidth: 2,
    borderColor: theme.colors.border.light,
    borderRadius: 4,
    marginRight: theme.spacing.sm,
    marginTop: 2,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: theme.colors.background.secondary,
  },
  checkboxChecked: {
    backgroundColor: theme.colors.primary.main,
    borderColor: theme.colors.primary.main,
  },
  agreementTextContainer: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap',
    alignItems: 'center',
  },
  agreementText: {
    ...theme.typography.body.small,
    color: theme.colors.text.secondary,
    lineHeight: 20,
    marginLeft: 4
  },
  agreementLink: {
    ...theme.typography.body.small,
    color: theme.colors.primary.main,
    fontWeight: '500',
    textDecorationLine: 'underline',
    lineHeight: 20,
  },
  
  // 注册按钮
  registerButton: {
    backgroundColor: theme.colors.primary.main,
    borderRadius: theme.borderRadius.md,
    paddingVertical: theme.spacing.md,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: theme.spacing.lg,
    ...theme.shadows.sm,
  },
  registerButtonDisabled: {
    backgroundColor: theme.colors.neutral.gray[400],
  },
  registerButtonText: {
    ...theme.typography.button.large,
    color: theme.colors.primary.contrast,
  },
  
  // 登录链接
  loginContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  loginPrompt: {
    ...theme.typography.body.medium,
    color: theme.colors.text.secondary,
    marginRight: theme.spacing.xs,
  },
  loginLink: {
    ...theme.typography.body.medium,
    color: theme.colors.primary.main,
    fontWeight: '500',
  },
  
  // 底部协议同意复选框样式
  bottomAgreementContainer: {
    paddingHorizontal: theme.spacing.md,
    paddingBottom: theme.spacing.lg,
  },
  checkboxContainer: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    paddingHorizontal: theme.spacing.sm,
  },
  checkbox: {
    width: 20,
    height: 20,
    borderWidth: 2,
    borderColor: theme.colors.border.light,
    borderRadius: 4,
    marginRight: theme.spacing.sm,
    marginTop: 2,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: theme.colors.background.secondary,
  },
  checkboxChecked: {
    backgroundColor: theme.colors.primary.main,
    borderColor: theme.colors.primary.main,
  },
  agreementTextContainer: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap',
    alignItems: 'center',
  },
  agreementText: {
    ...theme.typography.body.small,
    color: theme.colors.text.secondary,
    lineHeight: 20,
  },
  agreementLink: {
    ...theme.typography.body.small,
    color: theme.colors.primary.main,
    fontWeight: '500',
    textDecorationLine: 'underline',
    lineHeight: 20,
  },
  
  // 验证码容器
  verificationContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  verificationInput: {
    flex: 1,
    marginRight: theme.spacing.sm,
  },
  sendCodeButton: {
    backgroundColor: theme.colors.primary.main,
    borderRadius: theme.borderRadius.md,
    paddingHorizontal: theme.spacing.md,
    paddingVertical: theme.spacing.sm,
    minWidth: 80,
    minHeight: 48,
    alignItems: 'center',
    justifyContent: 'center',
    ...theme.shadows.sm,
  },
  sendCodeButtonDisabled: {
    backgroundColor: theme.colors.neutral.gray[400],
  },
  sendCodeButtonCountdown: {
    backgroundColor: theme.colors.neutral.gray[300],
  },
  sendCodeButtonSending: {
    backgroundColor: theme.colors.primary.light,
  },
  sendCodeText: {
    ...theme.typography.body.small,
    color: '#FFFFFF',
    fontWeight: '500',
  },
  sendCodeTextDisabled: {
    color: '#FFFFFF',
  },
  sendCodeTextCountdown: {
    color: '#FFFFFF',
    fontWeight: '600',
    fontSize: 14,
  },
  sendCodeTextSending: {
    color: '#FFFFFF',
    fontWeight: '500',
  },
});

export default RegisterView;